package com.sweetcircle.utils;

import com.sweetcircle.domain.vo.UserInfoVO;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 中文转拼音工具类
 */
public class PinyinUtils {
    /**
     * 获取汉字串拼音，英文字符不变
     */
    public static String getFullSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }

    /**
     * 将集合数据按照汉字首字母分组排序
     *
     * @param list 要排序的集合
     */
    public static HashMap<String, List<UserInfoVO>> sortFirstLetterUserInfo(List<UserInfoVO> list) {
        HashMap<String, List<UserInfoVO>> res = new HashMap<>();
        try {
            for (UserInfoVO userInfoVO : list) {
                Method declaredMethod = userInfoVO.getClass().getDeclaredMethod("getNickName");
                String name = (String) declaredMethod.invoke(userInfoVO);
                String fullSpell = getFullSpell(name);
                String key = fullSpell.substring(0, 1);  // 获取改昵称的英文首字母
                List<UserInfoVO> userInfoVOS = res.get(key);
                if (userInfoVOS == null) {
                    userInfoVOS = new ArrayList<>();
                    userInfoVOS.add(userInfoVO);
                } else {
                    userInfoVOS.add(userInfoVO);
                }
                res.put(key, userInfoVOS);
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        HashMap<String, List<Integer>> result = new HashMap<>();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(1);
        result.put("A", integers);
        System.out.println(result);
        List<Integer> a = result.get("A");
        a.add(2);
        a.add(3);
        System.out.println(result);

    }
}
